//
//  CHSAnimationController.m
//  ZXAnimationUtil_Example
//
//  Created by 朱新明 on 2023/7/3.
//  Copyright © 2023 simon. All rights reserved.
//

#import "CHSAnimationController.h"
#import <ZXTimer/ZXTimer.h>
#import <ZXCategoriesUtil/CAICategories.h>
#import "CHSAnimationLayer.h"
#import <ZXAnimationUtil/ZXAnimationUtil.h>
#import <Metal/Metal.h>

@interface CHSAnimationController ()<CALayerDelegate>

@property (nonatomic, strong) CHSAnimationLayer *layer;

@property (nonatomic, strong) CAReplicatorLayer *replicatorLayer;

///进度监视
@property (nonatomic, strong) CAReplicatorLayer *circleReplicatorLayer;

@end

@implementation CHSAnimationController

- (void)dealloc{
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [self animateLayer];

    [self addReplicatorLayer];
//    [self addGradientLayer];
//    [self addAudioFrequencyReplicatorLayer];
//    [self addCircleReplicatorLayer];
//    NSArray *arr = nil;
//    NSUInteger topIndex = [arr indexOfObjectPassingTest:^BOOL(__kindof id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        return [obj isEqualToString:@"2"];
//    }];
//
//    NSUInteger index = [arr indexOfObject:@"2"];
    
//    [self addOffscreenDraw];
}



- (void)animationLayerDraw{
    CHSAnimationLayer *layer = [CHSAnimationLayer layer];
    [self.view.layer addSublayer:layer];
    layer.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5].CGColor;
    layer.frame = CGRectMake(0,70, 300, 500);
    [layer setNeedsDisplay];
}






- (void)animateLayer{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 100, UIScreen.mainScreen.bounds.size.width, 100)];
    view.layer.backgroundColor = [UIColor redColor].CGColor;
    [self.view addSubview:view];
    [view.layer addSublayer:self.layer];
    
}



#pragma mark - 渐变图层

- (void)addGradientLayer{
    CAGradientLayer *gradient = [CALayer gradientLayerWithFrame:CGRectMake(0, 300, 100, 100) colors:@[(id)[UIColor blueColor].CGColor, (id)[UIColor greenColor].CGColor,(id)[UIColor orangeColor].CGColor] locations:@[@(0.25),@(0.5),@(0.75)] startPoint:CGPointMake(0, 0) endPoint:CGPointMake(0, 1)];
    [self.view.layer addSublayer:gradient];
}

#pragma mark - 简单的复制图层

- (void)addReplicatorLayer{
    CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer];
    replicatorLayer.bounds = CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, 100);
    replicatorLayer.position = self.view.center;
    int instanceCount = 6;
    CGFloat itemWidth = UIScreen.mainScreen.bounds.size.width/6 -10;
    
    CALayer *layer = [CALayer layer];
    layer.backgroundColor = [UIColor whiteColor].CGColor;
    layer.frame = CGRectMake(0, 0, itemWidth, itemWidth);
    [replicatorLayer addSublayer:layer];
    
    replicatorLayer.instanceCount = instanceCount;
    ///设置每次复制的3D变换
    replicatorLayer.instanceTransform = CATransform3DMakeTranslation(itemWidth+10, 0, 0);
    ///设置每次复制的颜色偏移
    CGFloat offsetStep = -1 / floorf(instanceCount);
    replicatorLayer.instanceBlueOffset = offsetStep;
    replicatorLayer.instanceGreenOffset = offsetStep;
    [self.view.layer addSublayer:replicatorLayer];
}



#pragma mark - 动画的圆形监视器复制图层

- (void)addCircleReplicatorLayer{
    ///添加复制图层；复制图层的Getter方法会添加子图层；
    [self.view.layer addSublayer:self.circleReplicatorLayer];

    ///设置小圆点图层
    self.layer.frame = CGRectMake(0, 0, 5, 5);
    self.layer.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.6].CGColor;
    self.layer.cornerRadius = CGRectGetHeight(self.layer.frame)/2;
    ///在复制图层的位置
    self.layer.position = CGPointMake(10, CGRectGetHeight(self.circleReplicatorLayer.bounds)/2);

    
    ///复制图层，直接创建30个点，用动画连贯起来
    NSInteger instanceCount = 30;
    self.circleReplicatorLayer.instanceCount = instanceCount;
    ///获取一个图层动画的duration持续时间
    CABasicAnimation *baseAnimation = [self.layer animationForKey:@"circle"];
    CFTimeInterval duration = baseAnimation?baseAnimation.duration:1.0;
    ///每个图层的动画延迟时间，用平均值，一个图层动画完，刚好一圈跑完。
    self.circleReplicatorLayer.instanceDelay = duration / floorf(instanceCount);
    ///360度平均角度
    CGFloat angle = (-2*M_PI) / floorf(instanceCount);
    self.circleReplicatorLayer.instanceTransform = CATransform3DMakeRotation(angle, 0, 0, 1);
    
    ///添加每个图层的显式动画
    [self addCircleAnimation];
}

///设置复制图层的bounds大小，背景色，圆角，position位置。添加子图层。
- (CAReplicatorLayer *)circleReplicatorLayer{
    if (!_circleReplicatorLayer) {
        CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer replicatorLayerWithSublayer:self.layer];
        replicatorLayer.bounds = CGRectMake(0, 0, 100, 100);
        replicatorLayer.cornerRadius = 10;
        replicatorLayer.position = self.view.center;
        replicatorLayer.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.2].CGColor;
        _circleReplicatorLayer = replicatorLayer;
    }
    return _circleReplicatorLayer;
}

- (void)addCircleAnimation{
    CABasicAnimation *baseAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    baseAnimation.fromValue = @(1);
    baseAnimation.toValue = @(0);
    baseAnimation.duration = 1;
    baseAnimation.repeatCount = CGFLOAT_MAX;
    ///是否需要自己倒放动画，有些动画适合使用，有些不适合使用。进度圆圈的动画就不适合。
//    baseAnimation.autoreverses = YES;
//    baseAnimation.removedOnCompletion = NO;
//    baseAnimation.fillMode = kCAFillModeForwards;
    [self.layer addAnimation:baseAnimation forKey:@"circle"];
}


#pragma mark - 播放的音频复制图层
- (void)addAudioFrequencyReplicatorLayer{
   
    [self.view.layer addSublayer:self.replicatorLayer];

    CGFloat itemWidth = 10;
    CGFloat itemHeight = CGRectGetHeight(self.replicatorLayer.bounds);
    CGFloat itemMagin = 5;
    self.layer.frame = CGRectMake(itemMagin, 0, itemWidth, itemHeight);
    ///设置Y缩放到0.2
    self.layer.transform = CATransform3DScale(self.layer.transform, 1, 0.2, 1);
    ///把瞄点定义在Y最大值
    self.layer.anchorPoint = CGPointMake(0.5, 1);
    
    
    CGFloat replicatorLayerWidth = CGRectGetWidth(self.replicatorLayer.bounds);
    NSInteger instanceCount = replicatorLayerWidth/(2*itemMagin+itemWidth);
    self.replicatorLayer.instanceCount = instanceCount;
    ///设置每次复制的变换，平移变换
    self.replicatorLayer.instanceTransform = CATransform3DMakeTranslation(2*itemMagin+itemWidth, 0, 0);
//    ///设置每次复制的颜色偏移
//    CGFloat offsetStep = -1 / floorf(instanceCount);
//    self.replicatorLayer.instanceRedOffset = offsetStep;
//    self.replicatorLayer.instanceBlueOffset = offsetStep;
    self.replicatorLayer.instanceDelay = 0.1;
    
    [self startAnimation];
}

- (CAReplicatorLayer *)replicatorLayer{
    if (!_replicatorLayer) {
        CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer replicatorLayerWithSublayer:self.layer];
        replicatorLayer.bounds = CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, 100);
        replicatorLayer.position = self.view.center;
        replicatorLayer.backgroundColor = [UIColor whiteColor].CGColor;
        _replicatorLayer = replicatorLayer;
    }
    return _replicatorLayer;
}

- (CHSAnimationLayer *)layer{
    if (!_layer) {
        CHSAnimationLayer *layer = [CHSAnimationLayer layer];
        layer.backgroundColor = [UIColor orangeColor].CGColor;
        _layer = layer;
    }
    return _layer;
}

- (void)startAnimation{
    CABasicAnimation *baseAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.y"];
    baseAnimation.toValue = @(1.0);
    baseAnimation.fromValue = @(0);
    baseAnimation.repeatCount = MAXFLOAT;
    baseAnimation.duration = 1.5;
    baseAnimation.autoreverses = YES;
//    baseAnimation.removedOnCompletion = NO;
//    baseAnimation.fillMode = kCAFillModeForwards;
    [self.layer addAnimation:baseAnimation forKey:@""];
}







//- (nullable id<CAAction>)actionForLayer:(CALayer *)layer forKey:(NSString *)event{
//    return [NSNull null];
//}


- (IBAction)testButtonAction:(id)sender {
//    [CATransaction begin];
//    [CATransaction setAnimationDuration:3];
////    [CATransaction setDisableActions:YES];
//    int a = (int)UIScreen.mainScreen.bounds.size.width-100;
//    self.layer.frame = CGRectMake(arc4random() % a, 0, 100, 100);
//    CAMediaTimingFunction *function = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionLinear];
//    [CATransaction setAnimationTimingFunction:function];
//    [CATransaction setCompletionBlock:^{
//
//    }];
//    [CATransaction commit];

    
    CABasicAnimation *opacityAnim = [CABasicAnimation animationWithKeyPath:@"position"];
    
    CGPoint positionFrom = CGPointMake(self.layer.frame.origin.x+CGRectGetWidth(self.layer.bounds)*self.layer.anchorPoint.x, self.layer.frame.origin.y+CGRectGetHeight(self.layer.bounds)*self.layer.anchorPoint.y);
    opacityAnim.fromValue = [NSValue valueWithCGPoint:positionFrom];
    
    int x = (int)UIScreen.mainScreen.bounds.size.width-100;
    int originX = arc4random() % x;
    CGPoint positionTo = CGPointMake(originX+CGRectGetWidth(self.layer.bounds)*self.layer.anchorPoint.x, positionFrom.y);
    opacityAnim.toValue = [NSValue valueWithCGPoint:positionTo];
    opacityAnim.removedOnCompletion = YES;
    opacityAnim.duration = 2;
    [self.layer addAnimation:opacityAnim forKey:nil];
}






- (void)timerAnimation{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 100, 100)];
    view.backgroundColor = [UIColor redColor];
    [self.view addSubview:view];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1/60.f repeats:YES block:^(NSTimer * _Nonnull timer) {
        
        if (view.frame.origin.x < UIScreen.mainScreen.bounds.size.width-100) {
            CGRect rect = view.frame;
            rect.origin.x = rect.origin.x +1;
            view.frame = rect;
        }
    }];
    [timer fire];
}

- (void)displayLinkAnimation{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 100, 100)];
    view.tag = 101;
    view.backgroundColor = [UIColor redColor];
    [self.view addSubview:view];
    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];
    [link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}
- (void)update{
    UIView *view = [self.view viewWithTag:101];
    if (view.frame.origin.x < UIScreen.mainScreen.bounds.size.width-100) {
        CGRect rect = view.frame;
        rect.origin.x = rect.origin.x +1;
        view.frame = rect;
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
